import {baseApi} from '../../../utils/util.js';
Page({
  data: {
    'openid':'',
    'visitorName':'',
    'visitorIdcard':'',
    'visitorPhone':'',
    'visitedIdcard':'',
    'visitedName':'',
    'visitedPhone':'',
    'visitedDept':'商务部',
    'etaDate':'2025-01-01',
    'etaTime':'09:01',
    'eta':'',
    'visitedDays':1,
    'carNum':'',
    'reason':'商务访问',
    'deptList':[],
    'reasonList':[],
    'staffList ':[]
  },
  onLoad: function() {
    var that = this;
    wx.getStorage({
      key: 'openid',
      success (res) {
        console.log(JSON.stringify(res));
        that.data.openid = res.data;
        console.log(res.data);
      }
    });
    this.getCurrentDate();
    this.getCurrentTime();
    this.getVisitorReason();
    this.getVisitedDept();
  },
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      etaDate: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      etaTime: e.detail.value
    })
  },
  addHandler(){
    //this.data.openid = wx.getStorage("openid");
    this.data.eta = this.data.etaDate +' '+this.data.etaTime;
    console.log(JSON.stringify(this.data));
    //进行前端验证
    if(!this.data.visitorName){
      wx.showToast({
        title: '请输入访客姓名',
      });
      return;
    }
    if(!this.data.visitorIdcard){
      wx.showToast({
        title: '请输入访客身份证号',
      });
      return;
    }
    if(!this.data.visitorPhone){
      wx.showToast({
        title: '请输入访客电话号码',
      });
      return;
    }
    if(!this.data.visitedDays){
      wx.showToast({
        title: '请输入访问天数',
      });
      return;
    }
    if(this.data.visitedDays>7){
      wx.showToast({
        title: '访问天数最做多7天',
      });
      return;
    }
    
    if(!this.data.etaDate){
      wx.showToast({
        title: '请输入到访日期',
      });
      return;
    }
    if(!this.data.etaTime){
      wx.showToast({
        title: '请输入到访时间',
      });
      return;
    }
    if(!this.data.reason){
      wx.showToast({
        title: '请输入访问事由',
      });
      return;
    }
    wx.showLoading({
      title: '正在提交... ...',
    })
    wx.request({
      method: 'POST',
      url: baseApi() + '/app/createVisitorAppointment',
      data: this.data,
      success(res){
        console.log(JSON.stringify(res));
        wx.hideLoading();
        if(res.data.code == 0){
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            success (res) {
              wx.navigateTo({
                url:  '/pages/visitor/list/index',
              });
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          });
        }else{
          wx.showToast({
            title: '预约失败！'+res.data.msg,
          });
        }
      }
    });
  },
  getCurrentDate(){
    var that = this;
    wx.request({
      method: 'POST',
      url:  baseApi() + '/app/getCurrentDate',
      success(res){
        var data = res.data.data;
        console.log(JSON.stringify(data));
        that.setData({'etaDate': data});
      }
    })
  },
  getCurrentTime(){
    var that = this;
    wx.request({
      method: 'POST',
      url:  baseApi() + '/app/getCurrentTime',
      success(res){
        var data = res.data.data;
        console.log(JSON.stringify(data));
        that.setData({'etaTime': data});
      }
    })
  },
  getVisitorReason(){
    var that = this;
    wx.request({
      method: 'POST',
      url:  baseApi() + '/app/getVisitorReason',
      success(res){
        var data = res.data.data;
        console.log(JSON.stringify(data));
        var list = [];
        for(var i=0; i<data.length; i++){
          list.push(data[i].dictLabel)
        }
        that.setData({'reasonList': list});
      }
    })
  },
  getVisitedDept(){
    var that = this;
    wx.request({
      method: 'POST',
      url:  baseApi() + '/app/getVisitedDept',
      success(res){
        var data = res.data.data;
        console.log(JSON.stringify(data));
        var list = [];
        for(var i=0; i<data.length; i++){
          list.push(data[i].deptName)
        }
        that.setData({'deptList': list});
      }
    })
  },
  onReasonChange(e){
    var index = e.detail.value;
    console.log(JSON.stringify(e.detail));
    console.log(this.data.reasonList[index]);
    this.setData({
      'reason': this.data.reasonList[index]
    });
  },
  onDeptChange(e){
    var index = e.detail.value;
    console.log(JSON.stringify(e.detail));
    console.log(this.data.deptList[index]);
    this.setData({
      'visitedDept': this.data.deptList[index]
    });
  },
  addStaff(){
    console.log('addStaff... ...');
    console.log(JSON.stringify(this.data));
    var staffList = this.data.staffList;
    if(!staffList){
      staffList = new Array();
    }
    var index = 0;
    for(var i=0; i<staffList.length; i++){
      if(staffList[i].index >= index ){
        index = staffList[i].index;
      }
    }
    staffList.push({'index':index+1, 'name':'' , 'phone':''});
    this.setData({
      'staffList':staffList
    });
  },
  removeStaff(e){
    var index = e.currentTarget.dataset.id
    var staffList = this.data.staffList;
    const newArr = staffList.filter(item => item.index !== index);
    this.setData({
      'staffList':newArr
    });
  },
  // 输入处理
  handleInput(e) {
    var index  = e.currentTarget.dataset.id
    var field = e.currentTarget.dataset.field;
    const value = e.detail.value
    console.log("index "+index);
    console.log("field "+field);
    console.log("value "+value);
    //debugger;
    var staffList = this.data.staffList;
    var item = {};
    for(var i=0;i<staffList.length;i++){
      if(index == staffList[i].index){
        item = staffList[i];
      }
    }
    if('name' ==  field){
      item.name = value;
    }
    if('phone' ==  field){
      item.phone = value;
    }
    console.log(JSON.stringify(item));
    for(var i=0;i<staffList.length;i++){
      if(index == staffList[i].index){
        staffList[i] = item;
      }
    }
    console.log("--->"+JSON.stringify(staffList));
    this.setData({
      'staffList': staffList
    })
  },
 
  // 获取元素索引
  getIndex(index) {
    console.log( this.data.staffList);
    return this.data.staffList.findIndex(item => item.index === index)
  },
 
  // 提交验证
  handleConfirm() {
    const errors = []
    this.data.staffList.forEach(item => {
      const rule = item.rules?.find(rule => 
        rule.required && !item.value.trim() ||
        rule.pattern && !rule.pattern.test(item.value)
      )
      if(rule) errors.push(rule.message)
    })
 
    if(errors.length) {
      wx.showToast({
        title: errors[0],
        icon: 'none'
      })
      return
    }
    // 提交逻辑
    console.log('提交数据:', this.data.staffList)
  }
})
